<template>
  <div class="mod-config">
    <el-row :gutter="20">
      <!--类型数据-->
      <el-col :span="4" :xs="24" style="padding-left: 30px;padding-right: 10px">
        <div class="head-container">
          <el-input
            v-model="leiXingName"
            placeholder="请输入资讯类型"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px;"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="leiXingList"
            :props="props"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--数据-->
      <el-col :span="20" :xs="24">
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">

          <el-form-item>
            <el-input v-model="dataForm.suoShuLeiXingMingCheng" placeholder="所属类型名称" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="dataForm.biaoTi" placeholder="标题" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="dataForm.miaoShu" placeholder="描述" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <!--              <el-input v-model="dataForm.zhuangTai" placeholder="状态" clearable></el-input>-->
            <el-select v-model="dataForm.zhuangTai" clearable placeholder="状态">
              <el-option label="启用中" value='启用中'></el-option>
              <el-option label="已关闭" value='已关闭'></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="getDataList(1)">查询</el-button>
            <el-button type="primary" @click="addOrUpdateHandle()">新增
            </el-button>
            <el-button type="danger" @click="deleteHandle()"
                       :disabled="dataListSelections.length <= 0">批量删除
            </el-button>
          </el-form-item>
        </el-form>
        <el-table
          :data="dataList"
          border
          v-loading="dataListLoading"
          @selection-change="selectionChangeHandle"
          style="width: 100%;">
          <el-table-column
            label="选中"
            type="selection"
            header-align="center"
            align="center"
            width="50">
          </el-table-column>
          <el-table-column
            type="index"
            label="序号"
            header-align="center"
            align="center"
            width="50">
          </el-table-column>
          <el-table-column
            prop="biaoTi"
            header-align="center"
            align="center"
            label="标题">
          </el-table-column>
          <el-table-column
            prop="suoShuLeiXingMingCheng"
            header-align="center"
            align="center"
            label="所属类型名称">
          </el-table-column>

          <el-table-column
            prop="miaoShu"
            header-align="center"
            align="center"
            label="描述">
          </el-table-column>
          <el-table-column
            prop="zhuangTai"
            header-align="center"
            align="center"
            label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.zhuangTai"
                active-text="启用中"
                inactive-text="已关闭"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="启用中"
                inactive-value="已关闭"
                @change="updateZhuangt($event, scope.row.id)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="tianJiaShiJian"
            header-align="center"
            align="center"
            label="添加时间">
          </el-table-column>

          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small"
                         @click="infoHandle(scope.row.id)"><i class="el-icon-edit"></i>查看详情
              </el-button>
              <el-button type="text" size="small"
                         @click="addOrUpdateHandle(scope.row.id)"><i class="el-icon-edit"></i>修改
              </el-button>
              <el-button type="text" size="small"
                         @click="deleteHandle(scope.row.id)"><i class="el-icon-delete"></i>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>

      </el-col>
    </el-row>
    <!--      ==============================================-->

    <!-- 弹窗, 新增 / 修改 -->
    <el-dialog title="添加或编辑" :visible.sync="addOrUpdateVisible" :modal-append-to-body="false" :modal="false">
      <el-form :rules="dataRule" :model="dataSaveForm" ref="dataForm" @keyup.enter.native="dataFormSubmit()">
        <el-form-item hidden :label-width="'120px'" prop="id">
          <el-input v-model="dataSaveForm.id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属类型" :label-width="'120px'" prop="suoShuLeiXingID">
          <!--                            <el-input v-model="dataSaveForm.suoShuLeiXingID" autocomplete="off"></el-input>-->
          <treeselect ref="lxTree" v-model="dataSaveForm.suoShuLeiXingID" :options="leiXingList" :props="props"
                      style="width: 100%"
                      @valHandler="getSelected" placeholder="请选择归属类型"/>
        </el-form-item>
        <!--                        <el-form-item label="所属类型名称" :label-width="'120px'"  prop="suoShuLeiXingMingCheng">
                                    <el-input v-model="dataSaveForm.suoShuLeiXingMingCheng" autocomplete="off"></el-input>
                                </el-form-item>-->
        <el-form-item label="标题" :label-width="'120px'" prop="biaoTi">
          <el-input v-model="dataSaveForm.biaoTi" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" :label-width="'120px'" prop="miaoShu">
          <el-input type="textarea" v-model="dataSaveForm.miaoShu" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="'120px'" prop="zhuangTai">
          <!--                            <el-input v-model="dataSaveForm.zhuangTai" autocomplete="off"></el-input>-->
          <el-switch
            v-model="dataSaveForm.zhuangTai"
            active-text="启用中"
            inactive-text="已关闭"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="启用中"
            inactive-value="已关闭">
          </el-switch>
        </el-form-item>
        <el-form-item label="资讯图片" :label-width="'120px'" prop="tupian">
          <el-upload :action="uploadUrl" multiple
                     :before-upload="beforeUpload"
                     :on-success="handleSuccess"
                     :on-preview="handlePreview"
                     :on-remove="handleRemove"
                     :file-list="imgList"
                     accept=".jpg, .jpeg, .png, .gif"
                     list-type="picture-card">
            <i class="el-icon-plus"></i>
            <el-dialog :visible.sync="showPreview" :modal-append-to-body="false" :modal="false">
              <img width="100%" :src="picUrl" alt />
            </el-dialog>
          </el-upload>
        </el-form-item>
        <el-form-item label="来源" :label-width="'120px'" prop="laiYuan">
          <el-input v-model="dataSaveForm.laiYuan" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="qx()">取 消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确 定</el-button>
      </div>
    </el-dialog>


    <!-- 弹窗, 新增 / 修改 -->
    <el-dialog title="药材资讯资讯信息" :visible.sync="infoVisible">
      <div class="mod-config">
        <el-descriptions :column="2"  :colon="false" title="药材资讯详情" content-class-name="customConten" label-class-name="customelable">
          <!--                            <el-descriptions-item label="所属类型id">{{this.infoList.suoShuLeiXingID}}</el-descriptions-item>-->
          <el-descriptions-item label="标题" span="1">{{ this.infoList.biaoTi }}</el-descriptions-item>
          <el-descriptions-item label="所属类型名称" span="1">{{ this.infoList.suoShuLeiXingMingCheng }}
          </el-descriptions-item>
          <el-descriptions-item label="状态" span="1">{{ this.infoList.zhuangTai }}</el-descriptions-item>
          <el-descriptions-item label="添加时间" span="1">{{ this.infoList.tianJiaShiJian }}</el-descriptions-item>
          <el-descriptions-item label="描述" span="3">{{ this.infoList.miaoShu }}</el-descriptions-item>

          <el-descriptions-item label="图片"  span="3" >
            <el-image style="width: 200px; height: 200px;padding-right: 10px;"   v-if="tuPianDes"
                      v-for="(item, index) of tuPianDes"
                 :key="index"
                 :src=item
                 :preview-src-list="getPreviewImgList(tuPianDes,index)">
            </el-image>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="qxinfo()">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import treeselect from "../../../components/tree-select/index.vue";
import {treeDataTranslate} from "../../../utils";

export default {
  components: {treeselect},
  data() {
    return {
      dataForm: {
        suoShuLeiXingID: '',
        suoShuLeiXingMingCheng: '',
        biaoTi: '',
        miaoShu: '',
        zhuangTai: '',

      },
      dataSaveForm: {
        suoShuLeiXingID: '',
        suoShuLeiXingMingCheng: '',
        biaoTi: '',
        miaoShu: '',
        zhuangTai: '启用中',
        tuPian:'',
        laiYuan:''
      },
      dataRule: {
        suoShuLeiXingID: [
          {required: true, message: '所属类型不能为空', trigger: 'blur'}
        ],
        biaoTi: [
          {required: true, message: '不能为空', trigger: 'blur'}
        ],
        miaoShu: [
          {required: true, message: '不能为空', trigger: 'blur'}
        ],
        zhuangTai: [
          {required: true, message: '不能为空', trigger: 'blur'}
        ],

      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,

      infoList: [],
      infoLoading: false,
      infoVisible: false,
      leiXingList: [],
      props: { // 配置项（必选）
        value: 'id',
        label: 'leiXingMingCheng',
        children: 'children'
      },
      leiXingName: undefined,
      uploadUrl: this.$http.adornUrl('/api-file/file/upload'),
      showPreview: false,
      picUrl:'',
      imgList:[],
      tuPianIds:[],
      tuPianDes:[],
    }
  },

  activated() {
    this.getLeiXingList()
    this.getDataList()

  },
  watch: {
    // 根据名称筛选类型树
    leiXingName(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    updateZhuangt($event, id){
      // console.log($event)
      // console.log(id)
      var zt=$event
      this.$http({
        url: this.$http.adornUrl(`/api-trading/yaoCaiZiXun/yaoCaiZiXunZiXunXinXi/updateZhuangTai`),
        method: 'get',
        params: this.$http.adornParams({"id": id,"zhuangTai":zt})
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            message: data.msg,
            type: "success",
          });
        }else{
          this.$message.error("修改状态失败");
        }
      })
      this.getDataList()
    },
    //处理图片预览效果
    handlePreview(file) {
      debugger
      console.log('yulan'+file)
      this.picUrl = file.url;
      this.showPreview = true
    },
    beforeUpload(file) {
      const isLt100M = file.size / 1024 / 1024 < 100
      if (!isLt100M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      return isLt100M
    },
    handleSuccess(response, file, fileList) {
      // console.log(file)
      // console.log(fileList)
      if (response && response.code === 0) {
        this.tuPianIds.push(response.data)
      }
 /*     if (response && response.code === 0) {
        this.imgList.push(response.data)
        // file.url='/file/view/file?fileId='+response.data
        file.url=this.$http.adornUrl('/api-file/file/view/file?fileId=' + response.data)
      }*/

    },
    handleRemove(file, fileList) {
      console.log(this.tuPianIds)
      console.log(file)
      console.log(fileList)
      if(file.response){
        this.tuPianIds.remove(file.response.data)
      }else{
        var pid=file.url.substring(file.url.lastIndexOf("=")+1);
        console.log(pid)
        this.tuPianIds = $.grep(this.tuPianIds, function(value) {
          return value != pid;
        });
      }
      // this.deleteFileFire(file)
    },
    getPreviewImgList:function(imgList,index) {
      let arr = []
      let i = 0;
      for(i;i < imgList.length;i++){
        arr.push(imgList[i+index])
        if(i+index >= imgList-1){
          index = 0-(i+1);
        }
      }
      return arr;
    },
    getDataList(pageIndex) {
      if (pageIndex) {
        this.pageIndex = pageIndex
      }
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/api-trading/yaoCaiZiXun/yaoCaiZiXunZiXunXinXi/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          'suoShuLeiXingID': this.dataForm.suoShuLeiXingID,
          'suoShuLeiXingMingCheng': this.dataForm.suoShuLeiXingMingCheng,
          'biaoTi': this.dataForm.biaoTi,
          'miaoShu': this.dataForm.miaoShu,
          'zhuangTai': this.dataForm.zhuangTai,
          'tianJiaShiJian': this.dataForm.tianJiaShiJian,
          'guanLianYongHu': this.dataForm.guanLianYongHu,
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.data.records
          this.totalPage = Number(data.data.total)
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    qx() {
      this.addOrUpdateVisible = false;

    },
    // 筛选节点
    filterNode(value, data) {
      console.log(data)
      console.log(value)
      if (!value) return true;
      return data.leiXingMingCheng.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.dataForm.suoShuLeiXingID = data.id;
      this.getDataList();
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      $(".el-upload-list li").remove();
      this.getLeiXingList()
      this.dataSaveForm.suoShuLeiXingID = ''
      this.dataSaveForm.suoShuLeiXingMingCheng = ''
      this.imgList=[]
      this.tuPianIds=[]
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (id) {
          this.$http({
            url: this.$http.adornUrl(`/api-trading/yaoCaiZiXun/yaoCaiZiXunZiXunXinXi/getById`),
            method: 'get',
            params: this.$http.adornParams({"id": id})
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataSaveForm.id = data.data.id
              this.dataSaveForm.suoShuLeiXingID = data.data.suoShuLeiXingID;
              this.dataSaveForm.suoShuLeiXingMingCheng = data.data.suoShuLeiXingMingCheng;
              this.dataSaveForm.biaoTi = data.data.biaoTi;
              this.dataSaveForm.miaoShu = data.data.miaoShu;
              this.dataSaveForm.zhuangTai = data.data.zhuangTai;
              this.dataSaveForm.tuPian=data.data.tuPian;
              this.dataSaveForm.laiYuan=data.data.laiYuan;
              if(data.data.tuPian){
                this.imgList=[]
                this.tuPianIds=[]
               var tp=data.data.tuPian.split(',')
                for (let i = 0; i < tp.length; i++) {
                  this.imgList.push({
                    url:this.$http.adornUrl('/api-file/file/download/file?fileId=' + tp[i])
                  })
                  this.tuPianIds.push(tp[i])
                }

              }

            }
          })
        }
      })

    },
    getLeiXingList() {
      this.leiXingList = []
      this.$http({
        url: this.$http.adornUrl(`/api-trading/yaoCaiZiXun/yaoCaiZiXunZiXunLeiXing/allList`),
        method: 'get',
        // params: this.$http.adornParams({"id":id})
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.leiXingList = treeDataTranslate(data.data, 'id', 'parentId')
        }
      })
    },
    // 菜单树选中
    getSelected(e) {
      // console.log("444444444444")
      this.dataSaveForm.suoShuLeiXingID = e.id
      this.dataSaveForm.suoShuLeiXingMingCheng = e.leiXingMingCheng

    },
    qxinfo() {
      this.infoVisible = false;
    },
    // 新增 / 修改
    infoHandle(id) {
      this.infoVisible = true;
      this.infoList = [];
      this.tuPianDes=[];
      this.$http({
        url: this.$http.adornUrl(`/api-trading/yaoCaiZiXun/yaoCaiZiXunZiXunXinXi/getById`),
        method: 'get',
        params: this.$http.adornParams({"id": id})
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.infoList = data.data;
          if(data.data.tuPian){
            var tp= data.data.tuPian.split(",")
            for (let i = 0; i <tp.length ; i++) {
              this.tuPianDes.push(
                this.$http.adornUrl('/api-file/file/download/file?fileId=' + tp[i])
              )
            }

          }
          console.log(this.infoList)
        }
      })
    },
    // 删除
    deleteHandle(id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定要进行删除操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/api-trading/yaoCaiZiXun/yaoCaiZiXunZiXunXinXi/delByIds'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    // 表单提交
    dataFormSubmit() {
      if(this.tuPianIds){
        this.dataSaveForm.tuPian=this.tuPianIds.join(",")
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/api-trading/yaoCaiZiXun/yaoCaiZiXunZiXunXinXi/save`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataSaveForm.id || undefined,
              'suoShuLeiXingID': this.dataSaveForm.suoShuLeiXingID,
              'suoShuLeiXingMingCheng': this.dataSaveForm.suoShuLeiXingMingCheng,
              'biaoTi': this.dataSaveForm.biaoTi,
              'miaoShu': this.dataSaveForm.miaoShu,
              'zhuangTai': this.dataSaveForm.zhuangTai,
              'tuPian': this.dataSaveForm.tuPian,
              'laiYuan':this.dataSaveForm.laiYuan,
              // 'tianJiaShiJian': this.dataSaveForm.tianJiaShiJian,
              // 'guanLianYongHu': this.dataSaveForm.guanLianYongHu,
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.addOrUpdateVisible = false
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })


    },
  }
}
</script>
<style>
.customConten {
  color: rgb(19 35 29)
}

.customelable {
  color: rgb(19 35 29 / 77%);
  text-align: right;
  width: 120px;
  background-color: #10592a0d;
  font-weight: bold
}
</style>
